<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="coverUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="lodingShow" type="circle" :percentage="percent" class="progressClass" />
    </el-upload>
  </div>
</template>

<script>
import Cos from 'cos-js-sdk-v5'
const cos = new Cos({
  SecretId: 'AKIDV4S5XxEVeV4d3DgOFo66uqZO4exz3lV1', // 身份识别ID
  SecretKey: 'UVFisogeOr8C5mNtEOfnJbP5f5NyKo4H' // 身份秘钥
})
export default {
  data() {
    return {
      imageUrl: '', // 回填图片
      percent: 0, // 控制进度条
      lodingShow: false
    }
  },
  methods: {
    // 覆盖默认的上传方式
    coverUpload(res) {
      if (res.file) {
        this.lodingShow = true
        // console.log(res)
        cos.putObject({
          Bucket: 'cxl-1305308882', /* 存储桶名称 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: res.file.name, /* 文件名 */
          StorageClass: 'STANDARD', // 上传模式，标准模式
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
          // 进度条
            this.percent = progressData.percent * 100
            console.log(JSON.stringify(progressData))
          }
        }, (err, data) => {
          console.log(err || data)
          if (data.statusCode === 200) {
          // 注意this 指向
            this.imageUrl = `https:${data.Location}`
            // 加载完成之后隐藏进度条
            this.lodingShow = false
          }
        })
      }
    },
    // 上传成功自动调用
    handleAvatarSuccess(res, file) {
      // console.log(res)
      // console.log(file)
    },
    // 上传之前的校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="scss">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  // 圆形进度条
  .progressClass {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 99;
    background-color: transparent;
  }
</style>
